﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.Controls
{
    public partial class ContractListCtrl : BaseListControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
        }

        public View_Contracts contracts
        {
            get { return (View_Contracts)SourceObject; }
            set { SourceObject = value; }
        }

        public String OnClientUpdate
        {
            get
            {
                if (ViewState[ClientID + "_OnClientUpdate"] == null)
                    ViewState[ClientID + "_OnClientUpdate"] = "";
                return ViewState[ClientID + "_OnClientUpdate"].ToString();
            }
            set { ViewState[ClientID + "_OnClientUpdate"] = value; }
        }

        protected override void grid_OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                Button btn  = e.Item.FindControl("btnUpdateMemo") as Button;
                btn.OnClientClick = OnClientUpdate;
            }
        }

        protected override void grid_OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            base.grid_OnItemCreated(sender, e);
            if (e.Item.ItemType == ListItemType.Header)
            {
                e.Item.Attributes.Add("class", "");
            }
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return "PrintHandler.aspx?key=" + PrintKey;
        }

        protected void btnPrint_OnClick(object sender, EventArgs e)
        {
            PrintInvoice();
        }

        private void PrintInvoice()
        {
            try
            {
                InvoiceViewerCtrl ivcViewer = (InvoiceViewerCtrl)LoadControl(@"InvoiceViewerCtrl.ascx");
                if (hidInvoiceID.Value != "")
                    ivcViewer.LoadInvoiceByID(int.Parse(hidInvoiceID.Value));

                Session[PrintKey] = ivcViewer;
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ContractListCtrl.ascx.cs", "PrintInvoice", ex.StackTrace);
            }
        }
    }
}